package com.yc.c118s3plyqnzf.controller;

import com.yc.c118s3plyqnzf.entity.House;
import com.yc.c118s3plyqnzf.entity.Users;
import com.yc.c118s3plyqnzf.mapper.HouseMapper;
import com.yc.c118s3plyqnzf.vo.Result;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lcx
 * @since 2022-11-28
 */
@Controller
@RequestMapping("/c118s3plyqnzf/house")
public class HouseController {

    @Resource
    HouseMapper houseMapper;

    @GetMapping("query")
    @ResponseBody
    List<House> query(){
        return houseMapper.selectList(null);
    }

    @PostMapping("save")
    @ResponseBody
    public Result save(
            //@RequestBody
            @Valid House house, Errors error,
            @SessionAttribute Users loginedUser){
        if (error.hasErrors()){
            return new Result(0,"字段错误", error.getAllErrors());
        }
        if (house.getId() == null){
            house.setUserId(loginedUser.getId());
            house.setTypeId(1);
            house.setStreetId(1);
            houseMapper.insert(house);
        } else {
            houseMapper.updateById(house);
        }
        return new Result(1,"房屋添加成功！", null);
    }
}
